# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        numStr1 = ''
        numStr2 = ''
        while l1:
            numStr1 = str(l1.val) + numStr1
            l1 = l1.next
        while l2:
            numStr2 = str(l2.val) + numStr2
            l2 = l2.next
        num1 = int(numStr1)
        num2 = int(numStr2)

        sumStr = str(num1 + num2)
        sumStrLength = len(sumStr) - 1
        node = ListNode(0)
        pointer = node
        while sumStrLength >= 0:
            pointer.next = ListNode(int(sumStr[sumStrLength]))
            sumStrLength -= 1;
            pointer = pointer.next
        return node.next;

    def addTwoNumbersOptimize(self, l1: ListNode, l2: ListNode) -> ListNode:

        node = ListNode(0)
        pointer = node
        carry = 0  # 进位数
        while (l1 or l2):
            x = l1.val if l1 else 0
            y = l2.val if l2 else 0
            s = carry + x + y
            carry = s // 10
            pointer.next = ListNode(s % 10)
            pointer = pointer.next
            if (l1 != None):
                l1 = l1.next
            if (l2 != None):
                l2 = l2.next
        if (carry > 0):
            pointer.next = ListNode(1)
        return node.next


solution = Solution()
print(solution.addTwoNumbersOptimize([2, 4, 3], [5, 6, 4]))
